<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            placeholder="请输入昵称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="认证状态" prop="authStatus">
          <el-select v-model="queryParams.authStatus" placeholder="请选择认证状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_auth_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_user_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['beauty:user:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['beauty:user:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['beauty:user:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['beauty:user:export']"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" width="100" />
        <el-table-column label="手机号" align="center" prop="phone" width="120" />
        <el-table-column label="昵称" align="center" prop="nickname" width="150" />
        <el-table-column label="真实姓名" align="center" prop="realName" width="100" />
        <el-table-column label="证件类型" align="center" prop="docType" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.docType === 'idcard'" type="primary" size="small">身份证</el-tag>
            <el-tag v-else-if="scope.row.docType === 'passport'" type="success" size="small">护照</el-tag>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="证件号码" align="center" width="180">
          <template #default="scope">
            {{ scope.row.docType === 'passport' ? (scope.row.passportNo || '--') : (scope.row.idCard || '--') }}
          </template>
        </el-table-column>
        <el-table-column label="认证状态" align="center" prop="authStatus" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_auth_status" :value="scope.row.authStatus" />
          </template>
        </el-table-column>
        <el-table-column label="用户状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_user_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="" align="center" min-width="1" />
        <el-table-column label="操作" align="center" fixed="right" width="280">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['beauty:user:query']"
            >详情</el-button>
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['beauty:user:edit']"
            >修改</el-button>
            <el-button
              v-if="scope.row.status === '0'"
              link
              type="warning"
              @click="handleFreeze(scope.row)"
              v-hasPermi="['beauty:user:freeze']"
            >冻结</el-button>
            <el-button
              v-else-if="scope.row.status === '1'"
              link
              type="success"
              @click="handleUnfreeze(scope.row)"
              v-hasPermi="['beauty:user:freeze']"
            >解冻</el-button>
            <el-button
              v-if="scope.row.status !== '2'"
              link
              type="danger"
              @click="handleBlacklist(scope.row, true)"
              v-hasPermi="['beauty:user:blacklist']"
            >拉黑</el-button>
            <el-button
              v-else
              link
              type="success"
              @click="handleBlacklist(scope.row, false)"
              v-hasPermi="['beauty:user:blacklist']"
            >移出黑名单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" maxlength="18" />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in beauty_user_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" v-model="detailDialog.visible" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ detailDialog.data.userId }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailDialog.data.phone }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ detailDialog.data.nickname }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ detailDialog.data.realName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="证件类型">
          <el-tag v-if="detailDialog.data.docType === 'idcard'" type="primary" size="small">身份证</el-tag>
          <el-tag v-else-if="detailDialog.data.docType === 'passport'" type="success" size="small">护照</el-tag>
          <span v-else>--</span>
        </el-descriptions-item>
        <el-descriptions-item label="证件号码">
          {{ detailDialog.data.docType === 'passport' ? (detailDialog.data.passportNo || '--') : (detailDialog.data.idCard || '--') }}
        </el-descriptions-item>
        <el-descriptions-item label="认证状态">
          <dict-tag :options="beauty_auth_status" :value="detailDialog.data.authStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="用户状态">
          <dict-tag :options="beauty_user_status" :value="detailDialog.data.status" />
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyUser">
import { ref, reactive, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import { listUser, getUser, addUser, updateUser, delUser, freezeUser, unfreezeUser, addToBlacklist, removeFromBlacklist } from '@/api/beauty/user';
import type { UserQuery, UserVO, UserForm } from '@/api/beauty/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { beauty_user_status, beauty_auth_status } = toRefs<any>(proxy?.useDict('beauty_user_status', 'beauty_auth_status'));

const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const userList = ref<UserVO[]>([]);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const userFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  phone: undefined,
  nickname: undefined,
  authStatus: undefined,
  status: undefined
});

const dialog = reactive({
  visible: false,
  title: ''
});

const detailDialog = reactive({
  visible: false,
  data: {} as UserVO
});

const form = ref<UserForm>({
  phone: '',
  nickname: '',
  realName: '',
  idCard: '',
  status: '0'
});

const rules = reactive({
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
});

// 查询用户列表
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((response: any) => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: UserVO[]) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  reset();
  dialog.visible = true;
  dialog.title = '添加用户';
}

// 修改按钮操作
function handleUpdate(row?: UserVO) {
  reset();
  const userId = row?.userId || ids.value[0];
  getUser(userId).then((response: any) => {
    form.value = response.data;
    dialog.visible = true;
    dialog.title = '修改用户';
  });
}

// 详情按钮操作
function handleDetail(row: UserVO) {
  getUser(row.userId).then((response: any) => {
    detailDialog.data = response.data;
    detailDialog.visible = true;
  });
}

// 提交按钮
function submitForm() {
  userFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.userId) {
        updateUser(form.value).then(() => {
          ElMessage.success('修改成功');
          dialog.visible = false;
          getList();
        });
      } else {
        addUser(form.value).then(() => {
          ElMessage.success('新增成功');
          dialog.visible = false;
          getList();
        });
      }
    }
  });
}

// 取消按钮
function cancel() {
  dialog.visible = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    phone: '',
    nickname: '',
    realName: '',
    idCard: '',
    status: '0'
  };
  userFormRef.value?.resetFields();
}

// 删除按钮操作
function handleDelete(row?: UserVO) {
  const userIds = row?.userId ? [row.userId] : ids.value;
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delUser(userIds);
  }).then(() => {
    getList();
    ElMessage.success('删除成功');
  });
}

// 冻结用户
function handleFreeze(row: UserVO) {
  ElMessageBox.confirm('确认要冻结用户"' + row.nickname + '"吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return freezeUser(row.userId);
  }).then(() => {
    getList();
    ElMessage.success('冻结成功');
  });
}

// 解冻用户
function handleUnfreeze(row: UserVO) {
  ElMessageBox.confirm('确认要解冻用户"' + row.nickname + '"吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    return unfreezeUser(row.userId);
  }).then(() => {
    getList();
    ElMessage.success('解冻成功');
  });
}

// 黑名单操作
function handleBlacklist(row: UserVO, add: boolean) {
  const action = add ? '加入黑名单' : '移出黑名单';
  ElMessageBox.confirm('确认要' + action + '用户"' + row.nickname + '"吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return add ? addToBlacklist(row.userId) : removeFromBlacklist(row.userId);
  }).then(() => {
    getList();
    ElMessage.success(action + '成功');
  });
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有用户数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现导出功能
    ElMessage.success('导出成功');
  });
}

getList();
</script>
